/*
 * @Author: Drc
 * @Date: 2021-07-15 15:27:09
 * @LastEditTime: 2021-09-24 10:39:39
 * @LastEditors: Drc
 */
class Colors {
  /**
   * Add alpha to hex or rgb color
   * arguments:
   * p1 - hex color / R part of RGB
   * p2 - opacity / G part of RGB
   * p3 - B part of RGB
   * p4 - opacity
   */
  static rgba(p1: number | string, p2: number, p3?: number, p4?: number) {
    let hex
    let opacity
    let red
    let green
    let blue

    if (arguments.length === 2 && typeof p1 === 'string') {
      hex = p1
      opacity = p2
      hex = this.validateHex(hex)
      red = parseInt(hex.substring(0, 2), 16)
      green = parseInt(hex.substring(2, 4), 16)
      blue = parseInt(hex.substring(4, 6), 16)
    } else if (arguments.length === 4 && typeof p1 === 'number') {
      red = this.validateRGB(p1)
      green = this.validateRGB(p2)
      blue = this.validateRGB(p3)
      opacity = p4
    } else {
      throw new Error('rgba can work with either 2 or 4 arguments')
    }

    return `rgba(${red}, ${green}, ${blue}, ${opacity})`
  }

  static validateHex(value: string) {
    if (!/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(value)) {
      throw new Error(`${value} is invalid hex color`)
    }

    return value.replace('#', '')
  }

  static validateRGB(value: number) {
    if (isNaN(value) || value > 255 || value < 0) {
      throw new Error(`${value} is invalid rgb code, please use number between 0-255`)
    }

    return value
  }
}

export default Colors
